<?php

require_once ROOT_DIR.'models/User.php';

/**
 * Tries to edit the user with the given id and data and prints the view of the results.
 * @param int $id
 * @param string $loginName
 * @param string $firstName
 * @param string $lastName
 * @param string $password
 * @param string $email
 */
function editUser($id, $loginName, $newPassword, $oldPassword, $firstName, $lastName, $email){
	//check if user exists
	$user = User::getUser($id);
	if(!is_null($user)){
		if(($user->getID() == $_SESSION['USER_ID'] || $_SESSION['USER_NAME'] == 'admin') && $user->getLoginName() != 'admin'){
			if(!is_null($loginName) || !is_null($newPassword)){
				if(!is_null($oldPassword)){
					if($user->getPassword() != md5($oldPassword)){
						$res = new ResultJSON(true, session_id(), ERROR_INVALID_LOGIN);
						echo $res->renderView();
						return;
					}
				} else {
					$res = new ResultJSON(true, session_id(), ERROR_REQUEST_PARAM_MISSING);
					echo $res->renderView();
					return;
				}
			}
			
			if(!is_null($loginName)){
				//check if name is already in use
				if(!is_null(User::getUserByName($loginName))){
					$res = new ResultJSON(true, session_id(), ERROR_USER_NAME_ALREADY_IN_USE);
					echo $res->renderView();
					return;
				} else {
					$user->setLoginName($loginName);
				}
			}
			
			if(!is_null($newPassword)){
				$user->setPassword(md5($newPassword));
			}
			
			if(!is_null($firstName)){
				$user->setFirstName($firstName);
			}
			
			if(!is_null($lastName)){
				$user->setLastName($lastName);
			}
			
			if(!is_null($email)){
				$user->setEmail($email);
			}
			
			if($user->saveToDB()){
				if($user->getID() == $_SESSION['USER_ID']) $_SESSION['USER_PASSWORD'] = $user->getPassword();
				$res = new ResultJSON(false, session_id());
				$res->addItem('uID', $user->getID());
				echo $res->renderView();
			} else {
				$res = new ResultJSON(true, session_id(), ERROR_ACTION_FAILED);
				echo $res->renderView();
			}
		} else {
			$res = new ResultJSON(true, session_id(), ERROR_TODO_DOES_NOT_EXIST);
			echo $res->renderView();
		}
	} else {
		$res = new ResultJSON(true, session_id(), ERROR_USER_DOES_NOT_EXIST);
		echo $res->renderView();
	}
}

?>